package org.budo.graph.view;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.budo.support.slf4j.Slf4j;
import org.slf4j.Logger;

/**
 * @author lmw
 */
public class BudoGraphViewFilter extends AbstractBudoGraphViewSupport implements Filter {
    private static final Logger log = Slf4j.getLogger();

    private static final String USERS_FILE_KEY = "userFile";

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.initUserConf(filterConfig);

        String usersFileParameter = filterConfig.getInitParameter(USERS_FILE_KEY);
        if (null != usersFileParameter && !usersFileParameter.isEmpty()) {
            this.setUserFile(usersFileParameter);
        }

        log.info("#92 inited, this=" + this);
    }

    private void initUserConf(FilterConfig filterConfig) {
        String users = filterConfig.getInitParameter(USERS_CONFIG_KEY);
        if (null == users || users.trim().isEmpty()) {
            log.info("#40 initUserConf, users = " + users + ", filterConfig=" + filterConfig + ", this = " + this);
            return;
        }

        String[] userArray = users.split(";");
        if (null == userArray || userArray.length < 1) {
            log.error("users not configed !!!");
            return;
        }

        for (String userStr : userArray) {
            String[] user = userStr.split(":");
            if (null == user || user.length != 2) {
                log.error("users configed error, user1:pwd1;user2:pwd2");
                continue;
            }

            this.getUserMap().put(user[0], user[1]);
        }
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {
        boolean handleBudoGraphRequest = this.handleBudoGraphRequest((HttpServletRequest) req, (HttpServletResponse) resp);
        if (handleBudoGraphRequest) {
            // 处理成功
        } else {
            chain.doFilter(req, resp);
        }
    }

    @Override
    public void destroy() {
        log.info("#77 destroy, this=" + this);
    }
}
